﻿ package code
{

	import caurina.transitions.*;
	import code.interfaces.IDesqCore;
	import code.interfaces.IModuleBase;
	import code.events.GeminiEvent;
	import divinity.utils.log.Log;
	import flash.display.*;
	import flash.events.*;
	import flash.external.*;
	import flash.geom.*;
	import flash.net.*;
	import gemini.utils.*;
	public class Core extends Sprite 
	{
		/*
		*	USER AND FACEBOOK VARS 
		*/
		private var _owner:int;
		private var _user:Object;	//	Needs to be revised due to divinity user changes
		
		
		///
		///
		///
		//
		public var tempLoad:Object;	//	Will not bu used once loaders are changed
		private  var _config:Object;
		private var _path:String="";
		private var _container:Sprite;
		private var _container1:Sprite;
		private var _fixed:Sprite;
		private var _desk:Sprite;
		public var backimg=null;;
		public var _mods:Array;
		public var _lang:String;
		public var _nav:Nav;
		
		private var modinfo:MovieClip;
		private var speed:Number=.6;
		public var focusat;
		private var _internals={};
		//public var _admin;
		//public var _tutorials;
		private var loadtxt:String;
		private var dragging:int;
		private var _back:Sprite
		public var _focusing:int=0;
		public var _loc:Object=null;
		
		/*
		*
		*
		*/
		public var videoPlayer:*;
		public var flashPlayer:*;
		public var youtubePlayer:*;
		
		private var _log:Log = new Log("Desq Core");
		//
		//
		//
		public function Core()
		{
			_log.addLog(this, "core started");
			_owner=1097635733;
			_user=
			{
				permission:0
			}
			getLocation();			
			loadConfig();
			
		}
		private function onprog(e)	//	<-------------- Needs revising
		{
			var frm=Math.round((e.loadedsize/e.totalsize)*100);
			ldscale.scl.gotoAndStop(frm);
			ldscale.txt.text=loadtxt+frm+"%";
			
		}
		private function loadConfig()
		{
			_log.addLog(this,"Loading config");
			trace("laoding config");
			var ld=new LoadJSONs();
			ld.addFile("php/config.php",this,"tempLoad");
			
			ld.onComplete(setPermisions);			
			ld.loadFiles();
		}
		private function setPermisions(e)
		{
			_log.addLog(this,"Setting parmissions");
			_config=tempLoad;
			tempLoad=null;
			//trace("------>"+user.uid)
			/******
			*	CHECK USER LOGGED
			*/
			/*
			if(String(user.uid)=="undefined")
			{
				trace("**************** user not logged *****************");
				user.permission=2;
				
			}
			else
			{
				if(user.uid==owner)
				{
					trace("********** OWNER **********");
					user.permission=0;
				}
				else
				{
					trace("********** FRIEND ************");
					user.permission=1;
				}
			}*/
			loadModules();
		}
		private function loadModules()
		{
			_log.addLog(this, "loading modules");
			loadtxt="Loading myDesq ";
			var ld=new BulkLoader();
			ld.onProgress(onprog);
			
			ld.addFile("admin/admin.swf",_internals,"_admin");
			ld.addFile("tutorials/tutorials.swf",_internals,"_tutorials");
			if (config.props.backimg != "")
			{
				//trace("got _back");
				ld.addFile(config.props.backimg,this,"backimg");
			}
			for (var n=0; n<config.modules.length; n++)
			{
				//ld.addFile("modules/"+config.modules[n].clip,config.modules[n],"clip");
			}
			ld.onComplete(preloadingDone);
			ld.loadFiles();
		}
		private function preloadingDone(e)
		{
			_log.addLog(this, "Preloader done");
			teaser.gotoAndStop("end");
			Tweener.addTween
			(
			 	teaser,
				{
					alpha:0,
					time:.3,
					delay:.1,
					transition:"linear",
					onComplete:removeTeaser
				}
			 )
			Tweener.addTween
			(
			 	ldscale,
				{
					alpha:0,
					time:.3,
					transition:"linear"
					
				}
			 )
			
		}
		private function removeTeaser()
		{
			removeChild(teaser);
			removeChild(ldscale);
			init(0);
		}
		private function init(e)
		{
			_log.addLog(this, "Initiating");
			dragging=0;
			
			_lang = config.props.langs[1];
			_container=new Sprite();
			addChildAt(_container,0);
			_container1=new frnt();
			addChildAt(_container1,1);
			_fixed=new Sprite();
			addChildAt(_fixed,2);
			
			
			
			
			
			makeInfo();
			makeDesktop();//<<-------------------------------------------------------------------------------------
			makeNav();
			//makeTutorials();
			
			trace(Log.list);
			
			
		}
		/**
		 * Calling this function will set DESQ background image to specified image link 
		 * @param	image_link
		 */
		public function setBackimg(image_link:String)
		{
			trace(" ------ loading _back img "+image_link);
			var ld=new BulkLoader();
			ld.addFile(image_link,this,"backimg");
			ld.onComplete(makeBackground);
			ld.loadFiles();
		}
		private function makeNav()
		{
			_nav = new Nav(this);
			
			addChildAt(_nav,2);
			_nav.init();
		}
		private function makeTutorials()
		{
			addChild(_internals._tutorials);
			_internals._tutorials.mainframe=this;
						
		}
		private function makeInfo()
		{
			_log.addLog(this, "Making info layer");
			modinfo=new moduleinfo();
			modinfo.visible=false
			modinfo.x=mouseX;
			modinfo.y=mouseY;
			addChild(modinfo);
		}
		public function makeModule(md)
		{
			trace("making module "+md);
			var n=_mods.length;
			_mods[n]=new DeskModule(this);
			_mods[n].mod = md
			_mods[n].pinned = false;
			//md.mainframe=this;
			//_mods[n].mynum=n;
			//config.modules[n].clip.mainframe=this;
			//_mods[n].addChild(md);
			
			//md.x =  -  md.width / 2;
			//md.y =  -  md.height / 2;
			_mods[n].x=_desk.mouseX;
			_mods[n].y=_desk.mouseY;
			_mods[n].init();
			//_mods[n].startDrag(true);
			addListeners(_mods[n]);
			_internals._admin.addArrow(_mods[n]);
			
			
			_desk.addChild(_mods[n]);
			
			
		}
		private function addListeners(module:DeskModule)
		{
			module.addEventListener(GeminiEvent.MODULE_PINNED, pinModule);
		}
		private function makeDesktop()
		{
			
			_log.addLog(this,"Making desktop");
			_desk=new Sprite();
			_mods = [];
			for (var n=0; n<config.modules.length; n++)
			{
				_mods[n]=new DeskModule(this);
				_mods[n].mod=config.modules[n]
				_mods[n].delay=(n+1)*200;
				//_mods[n].mynum=n;
				//config.modules[n].clip.mainframe=this;
				//_mods[n].addChild(config.modules[n].clip);
				//config.modules[n].clip.x =  -  config.modules[n].clip.width / 2;
				//config.modules[n].clip.y =  -  config.modules[n].clip.height / 2;
				_mods[n].x=config.modules[n].x
				_mods[n].y=config.modules[n].y
				_mods[n].ssx=_mods[n].x;
				_mods[n].ssy=_mods[n].y;
				//_mods[n].x=50+((_mods[n].width)+30)*n+200;
				//_mods[n].y=50+(_mods[n].height)+50*n;
				//_mods[n].y=Math.random()*900+50
				_mods[n].rotation = Math.random() * 10 - 5;
				//_mods[n].cacheAsBitmap=true;
				_mods[n].init();
				addListeners(_mods[n]);
				_desk.addChild(_mods[n]);
				//Filters.addFilters(_mods[n],"DropShadowFilter,quality:3,distance:1,strength:.8,blurX:3,blurY:3");
			}
			/*
			*
			*/
			

			
			
			/*
			*
			*/
			
			_container.addChild(_desk);	
			makeBackground()			
			stage.addEventListener(MouseEvent.MOUSE_MOVE,mouseMoved);
			//initModules();
			
			//focusFistNavModule();
		}
		/**
		 * Function updates desktop background according to visible modules
		 */
		public function makeBackground(e:Object=null)
		{
			try
			{
				
				_container.removeChild(_back);
			}
			catch(e)
			{
				trace(e);
			}
			
			if (backimg != null)
			{
				_back=new Sprite();
				_back.alpha=1
				var m:Matrix=new Matrix();
				m.rotate(-.15);
				m.scale(.8,.8);
				_back.graphics.beginBitmapFill(backimg.bitmapData,m,1,1);
				_back.graphics.drawRect(-1000,-1000,1000+_desk.width*2.8,1000+_desk.height*4);
				_back.graphics.endFill();
				//_back.cacheAsBitmap=true;
				_container.addChildAt(_back,0);
				//_back.addEventListener(MouseEvent.MOUSE_DOWN,dragBack);
				//_back.addEventListener(MouseEvent.MOUSE_UP,dontDragBack);
				
				//_back.addEventListener(MouseEvent.MOUSE_DOWN,focusOnMouse);
			}
		}
		private function initModules()
		{
			for(var n=0;n<_mods.length;n++)
			{
				for(var prop in config.modules[n].params)
				{
					trace(prop);
					config.modules[n].clip[prop]=config.modules[n].params[prop];
				}
				try
				{
					config.modules[n].clip.init();
				}
				catch(e)
				{
					//trace(e);
				}
			}
		}
		//
		//
		/*
		 * Needs revision
		 * */
		public function dragBack(e)
		{
			//var rct=new Rectangle(-1000,-1000,_container.width-1000,_container.height-1000);
			//trace(_container.width,_container.height);
			_container.startDrag(false);
			dragging=1;
		}
		public function dontDragBack(e)
		{
			_container.stopDrag();
			dragging=0;
		}
		/*******************************************************************
		*
		*	PLAYERS START
		*
		*********************************************************************/
		/**
		 * Initiates video play with default video stream player
		 * @param	video
		 */
		public function playVideo(video:String)
		{			
			videoPlayer.playVideo(video)
		}
		/**
		 * Initiates video play from youtube by youtube video code
		 * @param	video
		 */
		public function playYoutube(video:String)
		{			
			youtubePlayer.playYoutube(video)
		}
		/**
		 * Initiates flash play of suplied flash link and flash size
		 * @param	flash link to flash
		 * @param	s flash dimensions
		 */
		public function playFlash(flash:String,s:Object)
		{
			//trace("playing flash "+v,"size "+s.w);
			
			flashPlayer.playFlash(flash,s)
		}
		/**********************************************************		
		*
		************************************************************/
		/**
		 * Recenters desktop so that module is in the center of the screen
		 * @param	me
		 * @param	dims
		 */
		public function reCenter(me:DeskModule,dims:Object=null)
		{
			//var n=me
			//me=config.modules[n].clip
			me=me.clip;
			if(dims==null)
			{
				me.x=-me.width/2
				me.y=-me.height/2
			}
			else
			{
				me.x=-dims.width/2
				me.y=-dims.height/2
			}
		}
		/**
		 * Shows full info of the selected module
		 * @param	module
		 */
		public function showInfo(module:*)
		{
			
			//trace("SHOWING INFO "+module);
			if(mouseX>400)
			{
				modinfo.gotoAndStop("left");
			}
			else
			{
				modinfo.gotoAndStop("right");
			}
			modinfo.tit.text=module.title[_lang]
			modinfo.txt.text=module.info[_lang]			
			modinfo.alpha = 0;
			modinfo.visible = true;
			Tweener.addTween
			(
			 	modinfo,
				{
					alpha:1,
					time:.1,
					transition:"easeInOutQuad"
				}
			 
			 )
			
		}
		/**
		 * Shows only a module title in the info pane
		 * @param	module
		 */
		public function showShortInfo(module:*)
		{
			
			modinfo.gotoAndStop("short");
			modinfo.tit.text=module.title[_lang]
					
			modinfo.alpha=0
			modinfo.visible=true;
			Tweener.addTween
			(
			 	modinfo,
				{
					alpha:1,
					time:.1,
					transition:"easeInOutQuad"
				}
			 
			 )
			
		}
		/**
		 * Shows smaller version of the info
		 * @param	module
		 */
		public function showMediumInfo(module:*)
		{
			
			modinfo.gotoAndStop("medium");
			modinfo.tit.text=module.title[_lang]+"\n"
			modinfo.txt.text=module.info[_lang]		
			//trace(e.info,_lang);
			modinfo.alpha=0
			modinfo.visible=true;
			Tweener.addTween
			(
			 	modinfo,
				{
					alpha:1,
					time:.1,
					transition:"easeInOutQuad"
				}
			 
			 )
			
		}
		/**
		 * hides info pane
		 */
		public function hideInfo()
		{
			modinfo.visible=false;
		}
		private function mouseMoved(e)
		{
			modinfo.x=mouseX;
			modinfo.y=mouseY;
			if(dragging)
			{
				_container1.x=_container.x;
				_container1.y=_container.y;
			}
		}
		//
		//
		/**
		 * Focuses view on the module by module number in array
		 * @param	num
		 */
		public function focusModule(num:int)
		{
			_focusing=1;
			Tweener.updateTime();
			var dx = _mods[num].x;
			var dy = _mods[num].y;
			var rot = _mods[num].rotation;
			
			focusat={x:dx,y:dy};
			

			Tweener.addTween(
			 _container,
			{
			x:400-dx,
			y:300-dy,
			//rotation:rot,
			time:speed,
			transition:"easeInOutQuad",
			onComplete:function(){_focusing=0;}
			
			}
			 
			 );
			Tweener.addTween(
			 _container1,
			{
			x:400-dx*1,
			y:300-dy*1,
			//rotation:rot,
			time:speed,
			transition:"easeInOutQuad"
			
			}
			 
			 );
			setLocation(dx,dy)
			
			
		}
		/**
		 * Focuses view on the clip
		 * @param	clp
		 */
		public function focusByClip(clp:Sprite)
		{
			
			Tweener.updateTime();
			_focusing=1;
				focusat=clp;
				var dx = clp.x;
				var dy = clp.y;
				var rot = clp.rotation;
				
				focusat={x:dx,y:dy};
				
				Tweener.addTween(
				 _container,
				{
				x:400-dx,
				y:300-dy,
				//rotation:rot,
				time:speed,
				transition:"easeInOutQuad",
				onComplete:function(){_focusing=0;}
				
				}
				 
				 );
				Tweener.addTween(
				 _container1,
				{
				x:400-dx*1,
				y:300-dy*1,
				//rotation:rot,
				time:speed,
				transition:"easeInOutQuad"
				
				}
				 
				 );
			setLocation(dx,dy)
			
		}
		
		/**
		 * Focuses view on the suplied coordinates
		 * @param	dx
		 * @param	dy
		 * @param	quick
		 */
		public function focusOnPos(dx:Number,dy:Number,quick:Boolean=false)
		{
			_focusing=1;
			if(!quick)
			{
			Tweener.updateTime();
				
	
				Tweener.addTween(
				 _container,
				{
				x:400-dx,
				y:300-dy,
				//rotation:rot,
				time:speed,
				transition:"easeInOutQuad",
				onComplete:function(){_focusing=0;}
				
				}
				 
				 );
				Tweener.addTween(
				 _container1,
				{
				x:400-dx*1,
				y:300-dy*1,
				//rotation:rot,
				time:speed,
				transition:"easeInOutQuad"
				
				}
				 
				 );
				focusat={x:dx,y:dy};
			}
			else
			{
				_container.x=400-dx;
				_container.y=300-dy;
				_container1.x=_container.x;
				_container1.y=_container.y;
			}
			setLocation(dx,dy)
			
			
		}
		
		
		private function focusOnMouse(e)
		{
			focusOnPos(_container.mouseX,_container.mouseY)
		}
		private function pinModule(e:GeminiEvent)
		{
			trace("PINNING ", e.target);
			_nav.pinModule(e.target);
		}
		
		
		public function setToFront(c)
		{
			
			//var fac_x=_container1.x-_container.x;
			//var fac_y=_container1.y-_container.y;
			_container1.addChild(c);
			//c.ssx-=fac_x;
			//c.ssy-=fac_y;
			
		}
		public function setToBack(c)
		{
			
			_container.addChild(c);
			/*c.x=c.ssx;
			c.y=c.ssy;
			*/
		}
		/*
		*
		*
		*/
		public function setLocation(lx,ly)
		{
			
			var rr = new URLRequest("#loc:" +lx+","+ly);
			//navigateToURL(rr,"_self");
			
		}
		public function getLocation()
		{
			trace(ExternalInterface);
			//txt.text="Getting location";
			
			/*var cl=ExternalInterface.call("getUrl");
			if(cl.indexOf("#")!=-1)
			{				
				
				var str=cl.substr(cl.indexOf("#"),cl.length);
				str=str.substr(str.indexOf(":")+1,str.length);
				
				_loc={};
				_loc.x=int(str.substr(0,str.indexOf(",")));
				_loc.y=int(str.substr(str.indexOf(",")+1,str.length));
				txt.text="> "+_loc.x+":"+_loc.y;
			}
			else
			{
				_loc=null;
			}
			*/
			
		}
		
		/*
		*	GETTERS FOR CORE
		*
		*/
		public function get location():Object
		{
			return _loc;
		}
		public function get container():Sprite
		{
			return _container;
		}
		public function get container1():Sprite
		{
			return _container1;
		}
		public function get fixed():Sprite
		{
			return _fixed;
		}
		public function get admin():*
		{
			return _internals._admin;
		}
		public function get config():Object
		{
			return _config;
		}
		public function get USER():Object
		{
			return _user;
		
		}
		public function get path():String
		{
			return _path;
		}
		public function get focusing():int
		{
			return _focusing;
		}
		public function get lang():String
		{
			return _lang;
		}
		public function get mods():Array
		{
			return _mods;
		}
		public function get back():Sprite
		{
			return _back;
		}
		public function get NAV():Nav
		{
			return _nav;
		}
		/*
		*
		*
		*
		*
		*/
		public function getClass(lib_mc:MovieClip, classLib:String):Class
		{
			return lib_mc.loaderInfo.applicationDomain.getDefinition(classLib)  as  Class;
		}

	}

}